package Util;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.swing.text.StyledEditorKit.BoldAction;

import org.apache.lucene.index.SegmentInfos.FindSegmentsFile;

public class EntityManagerAdpater {

	private static final  EntityManagerFactory emf=buildEntityManagerFactoy();
	
	
	private static EntityManagerFactory buildEntityManagerFactoy() {
		
		try{
			
			EntityManagerFactory programmaticEmf=null;
			
				programmaticEmf = Persistence
						.createEntityManagerFactory("manager1");
			
			
			return programmaticEmf;
			
			
		}
		catch (Exception e) {
			System.err.println("Initial SessionFactory creation failed." + e);
	        throw new ExceptionInInitializerError(e);
		}
		}
	public static EntityManagerFactory  getEntityManagerFactory () {
	       if(emf==null){
	    	   buildEntityManagerFactoy();
	       }
			
			return  emf;
	    }
		
		public  void persist (Object obj)
		{
			EntityManager em = emf.createEntityManager();
			em.getTransaction().begin();
			em.persist(obj);
			em.flush();
			em.getTransaction().commit();
			em.close();
		
		}
		public void update (String query){
			EntityManager em = emf.createEntityManager();
			em.getTransaction().begin();
			em.createNativeQuery(query).executeUpdate();
			em.flush();
			em.getTransaction().commit();
			em.close();
			
			
		}
		public void update (Object query){
			update (query,false);
		
		}
		public void update (Object query,boolean IfExsit){
			
			EntityManager em = emf.createEntityManager();
			em.getTransaction().begin();
			//em.createNativeQuery(query).executeUpdate();
			
			
			//em.remove(query);
			em.merge(query);
			//em.flush();
			em.getTransaction().commit();
			em.close();
			
		}
	
}
